<!-- 商品分类页面 -->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <el-row>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="showaddCateDialog"
          >添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table
        class="tree-table"
        :data="categoriesList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        border
        show-index
        index-text="#"
        :show-row-hover="false"
      >
        <template
          slot="isOk"
          slot-scope="scope"
        >
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted == false"
            style="color: lightgreen"
          ></i>
          <i
            class="el-icon-error"
            v-if="scope.row.cat_deleted == true"
            style="color: red"
          ></i>
        </template>
        <template
          slot="level"
          slot-scope="scope"
        >
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag
            type="success"
            v-if="scope.row.cat_level == 1"
          >二级</el-tag>
          <el-tag
            type="warning"
            v-if="scope.row.cat_level == 2"
          >三级</el-tag>
        </template>
        <template
          slot="setting"
          slot-scope="scope"
        >
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="settingCate(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deleteCate(scope.row)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item
          label="分类名称："
          prop="cat_name"
        >
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectKeys"
            :key="cascaderKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addCate"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类的对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="setCateDialogVisible"
      width="50%"
      @close="closeSetDialog"
    >
      <el-form
        :model="setCateForm"
        label-width="100px"
        :rules="setCateFormRules"
        ref="setCateFormRef"
      >
        <el-form-item
          label="分类名称："
          prop="cat_name"
        >
          <el-input v-model="setCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setCateDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="setCate"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Categories",
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      categoriesList: [],
      total: 0,
      addCateDialogVisible: false,
      setCateDialogVisible: false,
      setCateForm: {},
      addCateForm: {
        cat_name: "",
        // 父级分类的id
        cat_pid: 0,
        // 分类层级
        cat_level: 0,
      },
      // 父级分类的数据列表
      parentCateList: [],
      // 选中的父级分类的id数组
      selectKeys: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        // 是否可以选择任何一项 包括一级分类
        checkStrictly: true,
      },
      /* 解决的一个bug，每次调用cascader会选择一个options，
      使得档次cascader的options发生改变，下次再调用相同的cascader就会报错，
      故使用该cascaderKeys来调用不同的cascader */
      cascaderKeys: 0,
      // 添加分类的表单验证规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      setCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 将当前列定义为模板列 且定义模板名称为isOk
          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          // 将当前列定义为模板列 且定义模板名称为level
          type: "template",
          template: "level",
        },
        {
          label: "操作",
          // 将当前列定义为模板列 且定义模板名称为isOk
          type: "template",
          template: "setting",
        },
      ],
    };
  },
  created() {
    this.getCategories();
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get(`categories`, {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败！");
      this.categoriesList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCategories();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCategories();
    },
    showaddCateDialog() {
      this.cascaderKeys++;
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      this.parentCateList = [];
      const { data: res } = await this.$http.get(`categories`, {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类列表失败！");
      this.parentCateList = res.data;
    },
    // 选择项发生变化
    parentCateChange() {
      /* 如果this.selectKeys.length>0 则说明选择了父级分类，
         则将父级的id和level保存下来，否则使用默认的id和level
       */
      if (this.selectKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
        // 这里看接口文档就知道为什么不加1
        this.addCateForm.cat_level = this.selectKeys.length;
      } else {
        this.addCateForm.cat_level = 0;
        this.addCateForm.cat_pid = 0;
      }
    },
    closeDialog() {
      // 清空表单
      this.$refs.addCateFormRef.resetFields();
      this.selectKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    // 点击按钮添加新的分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) this.$message.error("请输入正确の分类名称！");
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201)
          return this.$message.error("添加分类失败！");
        this.$message.success("添加分类成功!");
        this.getCategories();
        this.addCateDialogVisible = false;
      });
    },
    async settingCate(id) {
      const { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.setCateForm = res.data;
      console.log(this.setCateForm);
      this.setCateDialogVisible = true;
    },
    async deleteCate(item) {
      const { data: res } = await this.$http.delete(
        `categories/${item.cat_id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getCategories();
      this.$message.success(res.meta.msg);
    },
    closeSetDialog() {
      this.$refs.setCateFormRef.resetFields();
      this.setCateDialogVisible = false;
    },
    async setCate() {
      const { data: res } = await this.$http.put(
        `categories/${this.setCateForm.cat_id}`,
        {
          cat_name: this.setCateForm.cat_name,
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getCategories();
      this.setCateDialogVisible = false;
    },
  },
};
</script>

<style  scoped>
.tree-table {
  margin-top: 15px;
}

.el-cascader {
  width: 100%;
}
</style>
